package com.kaili.basic.controller.web.v1;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.pojo.dto.*;
import com.kaili.basic.pojo.entity.BaseInStoreDetailEntity;
import com.kaili.basic.pojo.entity.BaseInStoreEntity;
import com.kaili.basic.pojo.vo.BaseInStoreDetailVO;
import com.kaili.basic.pojo.vo.BaseInStoreExportVO;
import com.kaili.basic.service.*;
import com.kaili.basic.version.ApiVersion;
import com.kaili.common.exception.RestException;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.ExcelUtil;
import com.kaili.common.util.LoginDetailUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.*;

@ApiVersion(1)
@RestController
@RequestMapping("/{api_version}")
@Transactional
@Api(tags = "入库管理", description = "入库管理")
public class BaseInStoreController {
    @Autowired
    private BaseInStoreService baseInStoreService;

    @Autowired
    private BaseInStoreDetailService baseInStoreDetailService;

    @Autowired
    private BaseStoreStockService storeStockService;

    @Autowired
    private BaseStoreAccountsService baseStoreAccountsService;

    @Autowired
    private WarehousingApplicationService warehousingApplicationService;

    @GetMapping("/inStore/orderNo")
    @ApiOperation(value = "查询订单号")
    public Long queryStoreOrderNo(){
        return baseInStoreService.queryStoreOrderNo();
    }

    @GetMapping("/inStore")
    @ApiOperation(value = "分页查询入库")
    public Page<BaseInStoreDetailVO> queryPageList(@ModelAttribute BaseInStoreQueryDto queryDto){
        return baseInStoreService.queryPageList(new Page<BaseInStoreDetailVO>(queryDto.getPage(),queryDto.getPageSize()),queryDto);
    }

    @GetMapping("/inStore/edit/{id}")
    @ApiOperation(value = "编辑查询入库")
    public BaseInStoreDetailVO queryInStoreDetail(@PathVariable("id") Long id){
        return baseInStoreService.queryInStoreDetail(new HashMap<String, Object>() {{
            put("id", id);
        }});
    }

    @GetMapping("/inStore/export")
    @ApiOperation(value = "入库明细导出")
    public void export(HttpServletResponse response,@ModelAttribute BaseInStoreQueryDto queryDto) throws RestException {
        List<BaseInStoreExportVO> list = baseInStoreService.export(queryDto);
        ExcelUtil.exportExcel(list,"入库管理","sheet1", BaseInStoreExportVO.class, UUID.randomUUID().toString()+".xls",response);
    }

    @GetMapping("/inStore/detail/{orderNo}")
    @ApiOperation(value = "查询库存明细")
    List<BaseInStoreDetailVO> queryDetailByOrderNo(@ApiParam("订单号") @PathVariable("orderNo")final String orderNo){
        return baseInStoreDetailService.queryDetailByOrderNo(new HashMap<String,Object>(){{put("orderNo",orderNo);}});
    }

    @PostMapping("/inStore")
    @ApiOperation(value = "新增入库")
    public RestStatus addInStore(@RequestBody BaseInStoreAddDto dto){
        //添加入库订单号
        if(StringUtils.isNotBlank(dto.getLinkOrderNo())){
            //申请入库业务处理........
            dto.setOrderNo(String.valueOf(queryStoreOrderNo()));
        }
        BaseInStoreEntity entity=new BaseInStoreEntity();
        BeanUtils.copyProperties(dto,entity);
        entity.setCreateBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
        entity.setCreateTime(new Date());
        //统计数量
        for (BaseInStoreDetailAddDto detail:dto.getDetailList()) {
            entity.setTotalTrays(entity.getTotalTrays()+detail.getTrays());
            entity.setTotalVo(entity.getTotalVo()+detail.getVolume());
            entity.setTotalWeight(entity.getTotalWeight()+detail.getWeight());
            entity.setAmount(entity.getAmount()+detail.getAmount());
        }

        baseInStoreService.insert(entity);
        //新增入库明细信息
        baseInStoreDetailService.bathInsert(dto.getDetailList(),dto.getOrderNo());
        if(StringUtils.isNotBlank(dto.getLinkOrderNo())){
            //申请入库业务处理........
            warehousingApplicationService.updateOrderWarehousing(dto.getDetailList(),dto.getLinkOrderNo());
        }
        return CommonStatus.ADD_OK;
    }

    @PutMapping("/inStore")
    @ApiOperation(value = "修改入库")
    public RestStatus updateInStore(@RequestBody BaseInStoreEditDto dto){
        //修改入库信息
        BaseInStoreEntity entity=new BaseInStoreEntity();
        BeanUtils.copyProperties(dto,entity);
        entity.setModifyBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
        entity.setModifyTime(new Date());
        //统计数量
        for (BaseInStoreDetailAddDto detail:dto.getDetailList()) {
            entity.setTotalTrays(entity.getTotalTrays()+detail.getTrays());
            entity.setTotalVo(entity.getTotalVo()+detail.getVolume());
            entity.setTotalWeight(entity.getTotalWeight()+detail.getWeight());
            entity.setAmount(entity.getAmount()+detail.getAmount());
        }
        baseInStoreService.updateById(entity);
        //删除原有库存关联
        baseInStoreDetailService.deleteByMap(new HashMap<String,Object>(){{put("order_no",dto.getOrderNo());}});
        //新增入库明细信息
        baseInStoreDetailService.bathInsert(dto.getDetailList(),dto.getOrderNo());
        return CommonStatus.UPDATE_OK;
    }


    @PutMapping("/inStore/audit")
    @ApiOperation(value = "入库审核")
    public RestStatus auditInStore(@RequestBody BaseInStoreAuditDto dto){
        //更改审核状态
        BaseInStoreEntity entity=baseInStoreService.selectById(dto.getId());
        //已经做过审核不做处理
        if(!("0".equals(entity.getIsAuduit()))){
            return CommonStatus.UPDATE_OK;
        }
        entity.setAuditBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
        entity.setAuditTime(new Date());
        entity.setAuditRemark(dto.getAuditRemark());
        entity.setIsAuduit(dto.getIsAudit());
        baseInStoreService.updateById(entity);
        //查询订单对应的入库明细
        List<BaseInStoreDetailEntity> detailList = baseInStoreDetailService.selectByMap(new HashMap<String, Object>() {{
            put("order_no", dto.getOrderNo());
        }});
        //生成真正库存列表
        storeStockService.bathInsert(detailList,baseInStoreService.selectById(entity.getId()).getSupplierId());
        //生成台账记录
        baseStoreAccountsService.insertBath(detailList);
        return CommonStatus.UPDATE_OK;
    }

    @DeleteMapping("/inStore/{id}")
    @ApiOperation(value = "删除入库")
    public RestStatus deleteInStore(@ApiParam("订单号id")@PathVariable("id") long id){
        BaseInStoreEntity entity=new BaseInStoreEntity();
        entity.setId(id);
        entity.setStatus("0");
        baseInStoreService.updateById(entity);
        return CommonStatus.DELETE_OK;
    }
}


